package demo.example.controller;

import demo.example.common.ApiRestResponse;
import demo.example.common.Constant;
import demo.example.exception.TTException;
import demo.example.exception.TTExceptionEnum;
import demo.example.model.pojo.Message;
import demo.example.model.pojo.User;
import demo.example.service.MessageService;
import demo.example.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Date 2022/7/13 19:33
 * @Created by wangle
 * @Description
 */
@RestController
@RequestMapping("/message")
@Api(value = "表单接口", tags = {"表单接口"})
public class MessageController {

    @Autowired
    MessageService messageService;

    /**
    * @Author: kwy
    * @Date: 2022/7/18 14:49
    * @Param:
    * @return:
    * @Description:
    */
    @GetMapping("/test")
    @ApiOperation("测试表单用户")
    public Message test(){
        return messageService.getMessage("15002766835");
    }

    /**
    * @Author: kwy
    * @Date: 2022/7/18 14:49
    * @Param:
    * @return:
    * @Description:
    */
    
    
    /**
     * 
     * @param message
     * @return
     * @throws TTException
     */
    @PostMapping("/submit")
    @ApiOperation("提交表单")
    public ApiRestResponse submit(@RequestBody  Message message) throws TTException {
        String name = message.getName();
        String sex = message.getSex();
        String phone = message.getPhone();
        Date now = new Date();
        message.setCreatetime(now);

        if (StringUtils.isEmpty(name)) {
            return ApiRestResponse.error(TTExceptionEnum.NEED_USER_NAME);
        }

        if (StringUtils.isEmpty(phone)) {
            return ApiRestResponse.error(TTExceptionEnum.NEED_PHONE);
        }

        if(!sex.equals("男") && !sex.equals("女")){
            return ApiRestResponse.error(TTExceptionEnum.SEX_ERROR);
        }

        if(phone.length()!=11){
            return ApiRestResponse.error(TTExceptionEnum.PHONE_ERROR);
        }

        Pattern pattern = Pattern.compile("^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$");
        Matcher matcher = pattern.matcher(phone);
        if(!matcher.matches()){
            return ApiRestResponse.error(TTExceptionEnum.PHONE_FORMAT_ERROR);
        }

        Message message_now = messageService.getMessage(phone);
        if(message_now!=null){
            return ApiRestResponse.error(TTExceptionEnum.PHONE_EXISTED);
        }else{
            int result = messageService.insertMessage(message);
            if(result==1){
                return ApiRestResponse.success(message);
            }else{
                return ApiRestResponse.error(TTExceptionEnum.INSERT_FAILED);
            }
        }
    }




}
